# _*_coding:utf8_*_

import json
import threading
from flask import Flask, request, send_file
from flask_socketio import SocketIO, emit
import zuizhonganran as arcom
import gongyingshangjisuan as gyscom
import zuizhonghewenning as hwncom
from flask_cors import CORS

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app, resource="*")

startFlag = False
gysStartFlag = False
hwnFlag = False


def calculate_progress(hexiao, douyin, quanmingxi, bucanjia):
        for progress, resu in arcom.startExcel(hexiao, douyin, quanmingxi, bucanjia):
            print(f'进度{progress}>>>结果{resu}')
            socketio.emit('progress', {'progress': progress, 'url': resu}, namespace="/test")
        global startFlag
        startFlag = False


def gongyingshangfunc(chengdan, gongyingshanga):
    try:
        for progress, resu in gyscom.startExcel(chengdan, gongyingshanga):
            print(f'进度{progress}>>>结果{resu}')
            socketio.emit('progress', {'progress': progress, 'url': resu}, namespace="/test")
        global gysStartFlag
        gysStartFlag = False
    except Exception as e:
        print(e)
        gysStartFlag = False


def hewenningfunc(shujutable, mendiantable, bucanjiatable, quantable):
    # try:
        for progress, resu in hwncom.startExcel(shujutable, mendiantable, bucanjiatable, quantable):
            print(f'进度{progress}>>>结果{resu}')
            socketio.emit('progress', {'progress': progress, 'url': resu}, namespace="/test")
        global hwnFlag
        hwnFlag = False
    # except Exception as e:
    #     print(e)
    #     print('错误')
    #     hwnFlag = False


@socketio.on('connecta', namespace='/test')
def connecta():
    socketio.emit('progress', {'progress': 1, 'url': 1}, namespace="/test")


@app.route('/download', methods=['GET'])
def downloadExcel():
    filename = request.args.get('fileName')
    print(filename)
    return send_file(f'excel_ar/out/{filename}', as_attachment=False)


@app.route('/arcom', methods=['POST'])
def arcomController():
    global startFlag
    if not startFlag:
        hexiao = request.files.get('hexiao').stream.read()
        douyin = request.files.get('douyin').stream.read()
        quanmingxi = request.files.get('quanmingxi').stream.read()
        bucanjia = request.files.get('bucanjia').stream.read()
        threading.Thread(target=calculate_progress, args=(hexiao, douyin, quanmingxi, bucanjia)).start()
        startFlag = True
        return json.dumps({"code": 0, "msg": "计算中"})
    else:
        print('安然的已经有一个在运行')
        return json.dumps({"code": -1, "msg": "已经有任务在运行"})


@app.route('/gongyingshang', methods=['POST'])
def gongyingshang():
    global gysStartFlag
    if not gysStartFlag:
        chengdan = request.files.get('chengdan').stream.read()
        gongyingshang = request.files.get('gongyingshang').stream.read()
        threading.Thread(target=gongyingshangfunc, args=(chengdan, gongyingshang)).start()
        gysStartFlag = True
        return json.dumps({"code": 0, "msg": "计算中"})
    else:
        print('高工的已经有一个在运行')
        return json.dumps({"code": -1, "msg": "已经有任务在运行"})


@app.route('/hewenning', methods=['POST'])
def hewenning():
    global hwnFlag
    if not hwnFlag:
        # shujutable, mendiantable, bucanjiatable, quantable
        shuju = request.files.get('shuju').stream.read()
        mendian = request.files.get('mendian').stream.read()
        bucanjia = request.files.get('bucanjia').stream.read()
        quan = request.files.get('quan').stream.read()
        threading.Thread(target=hewenningfunc, args=(shuju, mendian, bucanjia, quan)).start()
        hwnFlag = True
        return json.dumps({"code": 0, "msg": "计算中"})
    else:
        print('文宁的已经有一个在运行')
        return json.dumps({"code": -1, "msg": "已经有任务在运行"})


if __name__ == '__main__':
    socketio.run(app, port=6550, allow_unsafe_werkzeug=True)
